package com.parktech.sun.domain.repository.hibernate;

import org.hibernate.cfg.DefaultNamingStrategy;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.util.StringHelper;

/**
 * Created by IntelliJ IDEA.
 * User: lewis.wang
 * Date: 2010-7-16
 * Time: 2:00:52
 */
public class UnderscoreNamingStrategy extends DefaultNamingStrategy {

    public static final String CEETOP_TABLE_PREFIX = "SO_";

    public static final NamingStrategy INSTANCE = new UnderscoreNamingStrategy();

    protected UnderscoreNamingStrategy() {
    }

    public String classToTableName(String className) {
        return CEETOP_TABLE_PREFIX + addUnderscores(StringHelper.unqualify(className));
    }

    public String propertyToColumnName(String propertyName) {
        return addUnderscores(StringHelper.unqualify(propertyName));
    }

    public String tableName(String tableName) {
        return tableName;
    }

    public String columnName(String columnName) {
        return columnName;
    }

    @Override
    public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName) {
        if (propertyName != null) {
            return addUnderscores(propertyName) + "_id";
        } else {
            return addUnderscores(propertyTableName) + "_id";
        }
    }

    private String addUnderscores(String name) {
        StringBuffer buf = new StringBuffer(name.replace('.', '_'));
        for (int i = 1; i < buf.length() - 1; i++) {
            if ('_' != buf.charAt(i - 1) && Character.isUpperCase(buf.charAt(i)) && !Character.isUpperCase(buf.charAt(i + 1))) {
                buf.insert(i++, '_');
            }
        }
        return buf.toString().toLowerCase();
    }

}